﻿using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Localization;
using Rechargeable.Localization;
using Rechargeable.MultiTenancy;
using Rechargeable.Permissions;
using Volo.Abp.TenantManagement.Web.Navigation;
using Volo.Abp.UI.Navigation;

namespace Rechargeable.Web.Menus
{
    public class RechargeableMenuContributor : IMenuContributor
    {
        public async Task ConfigureMenuAsync(MenuConfigurationContext context)
        {
            if (context.Menu.Name == StandardMenus.Main)
            {
                await ConfigureMainMenuAsync(context);
            }
        }

        private async Task ConfigureMainMenuAsync(MenuConfigurationContext context)
        {
            var currentUser = context.ServiceProvider.GetRequiredService<Volo.Abp.Users.ICurrentUser>();
            if (currentUser != null && currentUser.IsAuthenticated)
            {
                if (!MultiTenancyConsts.IsEnabled)
                {
                    var administration = context.Menu.GetAdministration();
                    administration.TryRemoveMenuItem(TenantManagementMenuNames.GroupName);
                }

                var authorizationService = context.ServiceProvider.GetRequiredService<IAuthorizationService>();

                if (await authorizationService.IsGrantedAnyAsync(RechargeablePermissions.GetAll()) == false)
                {
                    return;
                }

                var l = context.ServiceProvider.GetRequiredService<IStringLocalizer<RechargeableResource>>();

                var homeMenu = new ApplicationMenuItem("Rechargeable.Home", l["Menu:Home"], "/", icon: "fa fa-home");
                homeMenu.AddItem(new ApplicationMenuItem("Rechargeable.Product", l["Menu:Products"], url: "/Products", icon: "fa fa-robot", requiredPermissionName: Permissions.RechargeablePermissions.Product));
                homeMenu.AddItem(new ApplicationMenuItem("Rechargeable.Machines", l["Menu:Machines"], url: "/Machines", icon: "fa fa-server", requiredPermissionName: Permissions.RechargeablePermissions.Machines));
                homeMenu.AddItem(new ApplicationMenuItem("Rechargeable.SerialNumber", l["Menu:SerialNumber"], url: "/SerialNumber", icon: "fa fa-fingerprint", requiredPermissionName: RechargeablePermissions.SerialNumber));
                context.Menu.Items.Insert(0, homeMenu);
                await Task.CompletedTask;
            }
        }
    }
}
